/*
 * SDK连接相关
 */

import config from '@/configs'
import {onMyInfo, onUserInfo} from './userInfo'
import { onSessions, onUpdateSession } from './session'
import { onRoamingMsgs, onOfflineMsgs, onMsg, onCustomSysMsgs } from './msgs'

import store from '../../'
const SDK = require('../../../../static/NIM_Web_SDK_v6.1.0')

// 重新初始化 NIM SDK
export function initNimSDK({ state, commit, dispatch }, loginInfo) {
  if (state.nim) {
    state.nim.disconnect()
  }
  // 初始化SDK
  window.nim = state.nim = SDK.NIM.getInstance({
    debug: false,
    appKey: config.appkey,
    account: loginInfo.uid,
    token: loginInfo.sdktoken,
    transports: ['websocket'],
    db: config.useDb,
    syncSessionUnread: true,
    onconnect: function onConnect(event) {
      if (loginInfo) {
        // 连接上以后更新uid
        commit('updateUserUID', loginInfo)
      }
    },
    onerror: function onError(event) {
      console.log(event)
    },
    onwillreconnect: function onWillReconnect(event) {
      console.log(event)
    },
    ondisconnect: function onDisconnect(error) {
      switch (error.code) {
        // 账号或者密码错误, 请跳转到登录页面并提示错误
        case 302:
          console.log('NIM => 帐号或密码错误')
          break
        // 被踢, 请提示错误后跳转到登录页面
        case 'kicked':
          let map = {
            PC: '电脑版',
            Web: '网页版',
            Android: '手机版',
            iOS: '手机版',
            WindowsPhone: '手机版'
          }
          let str = error.from
          // let errorMsg = `你的帐号于${util.formatDate(new Date())}被${(map[str] || '其他端')}踢出下线，请确定帐号信息安全!`
          // pageUtil.turnPage(errorMsg, 'login')
          break
        default:
          break
      }
    },
    // 同步完成
    onsyncdone: function onSyncDone() {
      // 说明在聊天列表页
      if (state.currSessionId) {
        dispatch('setCurrSession', state.currSessionId)
      }

      commit('initNimSuccess');
    },

    // 用户名片 - actions/userInfo
    onmyinfo: onMyInfo,
    onupdatemyinfo: onMyInfo,
    onusers: onUserInfo,
    onupdateuser: onUserInfo,

    // 会话
    onsessions: onSessions,
    onupdatesession: onUpdateSession,
    // 消息
    onroamingmsgs: onRoamingMsgs,
    onofflinemsgs: onOfflineMsgs,
    onmsg: onMsg,

    onofflinecustomsysmsgs: onCustomSysMsgs,
    oncustomsysmsg: onCustomSysMsgs,
  })
  window.nim.useDb = config.useDb
}
